import random

class Snake:
    def __init__(self, game_area_width, game_area_height):
        self.body = self.random_position(game_area_width, game_area_height)
        self.direction_vector = [1, 0]  # 初始方向向右
        self.acceleration = [0, 0]  # 初始加速度为0
        self.grow_flag = False

    def random_position(self, width, height):
        # 生成一个随机位置，确保不会与其他物体重叠
        game_area_width = int(width * 0.2)  # 左侧20%的游戏区域宽度
        position = [random.randrange(0, game_area_width, 20), random.randrange(0, height, 20)]
        return [position, [position[0] - 20, position[1]], [position[0] - 40, position[1]]]

    def change_direction(self, new_direction_vector):
        self.acceleration = new_direction_vector

    def update_direction(self):
        self.direction_vector[0] += self.acceleration[0]
        self.direction_vector[1] += self.acceleration[1]
        # 归一化方向向量
        length = (self.direction_vector[0]**2 + self.direction_vector[1]**2)**0.5
        if length > 0:
            self.direction_vector[0] /= length
            self.direction_vector[1] /= length

    def move(self):
        self.update_direction()  # 更新方向向量
        head_x, head_y = self.body[0]
        new_head = [head_x + self.direction_vector[0] * 20, head_y + self.direction_vector[1] * 20]

        self.body.insert(0, new_head)
        if not self.grow_flag:
            self.body.pop()
        else:
            self.grow_flag = False

    def grow(self):
        self.grow_flag = True

    def check_collision(self, width, height):
        head = self.body[0]
        if head[0] < 0 or head[0] >= width or head[1] < 0 or head[1] >= height:
            return True
        for segment in self.body[1:]:
            if segment == head:
                return True
        return False


class AISnake(Snake):
    def __init__(self, width, height):
        super().__init__(width, height)
        self.width = width
        self.height = height
        self.body = [[width // 2, height // 2 + 20], [width // 2, height // 2 + 40], [width // 2, height // 2 + 60]]
        self.acceleration = [0, 1]
        self.reset()  # 初始化时调用reset方法

    def reset(self):
        self.body = [[self.width // 2, self.height // 2 + 20], [self.width // 2, self.height // 2 + 40], [self.width // 2, self.height // 2 + 60]]
        self.acceleration = [0, 1]

    def move_towards_food(self, food_positions):
        head = self.body[0]
        closest_food = min(food_positions, key=lambda pos: (pos[0] - head[0]) ** 2 + (pos[1] - head[1]) ** 2)
        if head[0] < closest_food[0]:
            self.change_direction([1, 0])
        elif head[0] > closest_food[0]:
            self.change_direction([-1, 0])
        elif head[1] < closest_food[1]:
            self.change_direction([0, 1])
        elif head[1] > closest_food[1]:
            self.change_direction([0, -1])
        self.move()